package com.dmgameclient.fragments;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

import com.dmgameclient.R;
import com.dmgameclient.activities.DetailGameActivity;
import com.dmgameclient.adapter.GameGridViewAdapter;
import com.dmgameclient.beans.Game;
import com.dmgameclient.common.HttpUtils;
import com.dmgameclient.common.JsonUtils;
import com.dmgameclient.common.UIHelper;
import com.dmgameclient.common.URLHelper;
import com.dmgameclient.widget.CustomDialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @name FragmentGame
 * @Descripation <br>
 *               1、<br>
 *               2、<br>
 * @author 樊俊彬
 * @date 2014-9-20
 * @version 1.0
 */
public class FragmentGame extends Fragment {

	private static final String TAG = "FragmentGame";

	// 选取类型
	private Spinner spinner;
	private ArrayAdapter<String> spinnerAdapter;
	private List<String> types = new ArrayList<String>();

	// 内容GridView
	private GridView gridView;
	private GameGridViewAdapter gridAdapter;
	private List<Game> list = new ArrayList<Game>();
	private CustomDialog dialog;
	private Handler handler;

	// GridView列表底部视图
	private LinearLayout footerLayout;
	private TextView footerText;
	private ProgressBar footerProgress;

	// 复用页面，类型id和页码
	private String type;
	private int page = 1;

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		Log.i(TAG, ">>>onAttach");
	}

	public void onCreate(android.os.Bundle savedInstanceState) {
		Log.i(TAG, ">>>onCreate");
		super.onCreate(savedInstanceState);
		initSpinnerData();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>onActivityCreated");
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>onStart");
		super.onStart();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>onResume");
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>onPause");
		super.onPause();
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>onStop");
		super.onStop();
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>onDestroyView");
		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>onDestroy");
		super.onDestroy();
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		Log.i(TAG, ">>>onDetach");
		super.onDetach();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(TAG, ">>>onCreateView");
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_game_gridview,
				container, false);
		spinner = (Spinner) view.findViewById(R.id.spinner1);
		gridView = (GridView) view.findViewById(R.id.gridView1);

		// GridView底部视图
		footerLayout = (LinearLayout) view.findViewById(R.id.footerLayout);
		footerText = (TextView) footerLayout
				.findViewById(R.id.listview_foot_more);
		footerProgress = (ProgressBar) footerLayout
				.findViewById(R.id.listview_foot_progress);

		// 加载进度条对话框
		dialog = new CustomDialog(getActivity());

		initSpinner();
		initFrame();
		return view;
	}

	/**
	 * 加载Spinner下拉列表的数据，不能在onCreateView方法当中
	 */
	private void initSpinnerData() {
		String[] typeNames = new String[] {
				getResources().getString(R.string.typename_game_1),
				getResources().getString(R.string.typename_game_2),
				getResources().getString(R.string.typename_game_3),
				getResources().getString(R.string.typename_game_4),
				getResources().getString(R.string.typename_game_5),
				getResources().getString(R.string.typename_game_6),
				getResources().getString(R.string.typename_game_7),
				getResources().getString(R.string.typename_game_8),
				getResources().getString(R.string.typename_game_9),
				getResources().getString(R.string.typename_game_10),
				getResources().getString(R.string.typename_game_11),
				getResources().getString(R.string.typename_game_12) };
		for (int i = 0; i < typeNames.length; i++) {
			types.add(typeNames[i]);
		}
	}

	/**
	 * 为下拉选取类型绑定adapter,选中一个选项时开启线程下载数据
	 */
	private void initSpinner() {
		spinnerAdapter = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_spinner_item, types);
		spinner.setAdapter(spinnerAdapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				footerLayout.setVisibility(View.GONE);
				if (position == 0) {
					type = URLHelper.TYPE_GAME_1;
				} else if (position == 1) {
					type = URLHelper.TYPE_GAME_2;
				} else if (position == 2) {
					type = URLHelper.TYPE_GAME_3;
				} else if (position == 3) {
					type = URLHelper.TYPE_GAME_4;
				} else if (position == 4) {
					type = URLHelper.TYPE_GAME_5;
				} else if (position == 5) {
					type = URLHelper.TYPE_GAME_6;
				} else if (position == 6) {
					type = URLHelper.TYPE_GAME_7;
				} else if (position == 7) {
					type = URLHelper.TYPE_GAME_8;
				} else if (position == 8) {
					type = URLHelper.TYPE_GAME_9;
				} else if (position == 9) {
					type = URLHelper.TYPE_GAME_10;
				} else if (position == 10) {
					type = URLHelper.TYPE_GAME_11;
				} else if (position == 11) {
					type = URLHelper.TYPE_GAME_12;
				}
				// 初始化不作操作时加载1页数据
				dialog.show();
				downloadData(type, 1, UIHelper.ACTION_TYPE_INIT);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
			}
		});
	}

	@SuppressLint("HandlerLeak")
	private void initFrame() {
		// 为游戏内容绑定adapter
		gridAdapter = new GameGridViewAdapter(getActivity(),
				R.layout.item_gridview_game, list, gridView);
		gridView.setAdapter(gridAdapter);

		// 根据不同的操作刷新页面
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				// TODO Auto-generated method stub
				if (msg.obj != null) {
					switch (msg.arg1) {

					// 初始化
					case UIHelper.ACTION_TYPE_INIT:
						list.clear();
						break;

					// 滑动时不能清除数据
					case UIHelper.ACTION_TYPE_LOADMORE:
						gridView.setSelection(0);
						footerText.setText(R.string.load_more);
						break;
					default:
						break;
					}
					list.addAll((List<Game>) msg.obj);
					gridAdapter.notifyDataSetChanged();
					footerLayout.setVisibility(View.GONE);
				}
				dialog.dismiss();
			}
		};

		// 滚动到底部时依次加载2、3、4...页数据
		gridView.setOnScrollListener(new OnScrollListener() {
			boolean isBottom = false;
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO 捕获用户手势，是否飞滑到底部
				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL
						&& isBottom) {
					footerLayout.setVisibility(View.VISIBLE);
					downloadData(type, ++page, UIHelper.ACTION_TYPE_LOADMORE);
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem + visibleItemCount == totalItemCount
						&& !isBottom) {
					isBottom = true;
				} else {
					isBottom = false;
				}
			}
		});

		// 点击列表项时进入到游戏详细页面
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						DetailGameActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("gameObject", list.get(position));
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});

	}

	/**
	 * 启动线程下载数据
	 * 
	 * @param type
	 * @param page
	 * @param actionType
	 */
	public void downloadData(final String type, final int page,
			final int actionType) {
		Executors.newSingleThreadExecutor().execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = Message.obtain();
				String jsonString = HttpUtils.downloadString(
						URLHelper.getGameListUrl(type, page),
						URLHelper.BASE_URL);

				// 服务器返回错误数据，处理下才能解析
				if (jsonString != null) {
					String rightString = jsonString.substring(jsonString
							.indexOf("{\"data"));
					msg.arg1 = actionType;
					msg.obj = JsonUtils.parseGameList(rightString);
					handler.sendMessage(msg);
				}
			}
		});
	}
}
